// PlaySound.cpp: implementation of the CPlaySound class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "CoodTimer.h"
#include "PlaySound.h"
#include "myWnd.h"

extern CmyWnd g_Wnd;

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CPlaySound::CPlaySound(PSTR sSound,int nDuration)
:   m_sSound(_strdup(sSound)),
	m_nDuration(nDuration),
	m_hEventStop(CreateEvent(NULL,TRUE,FALSE,NULL)),
	m_psVal(NULL)

{

}

CPlaySound::~CPlaySound()
{
	if(m_sSound)
		free(m_sSound);
	if(m_hEventStop)
		CloseHandle(m_hEventStop);

}
void CPlaySound::Start(CPlaySound** psVal,bool bThread)
{
	m_psVal=psVal;
	if(bThread)
	{
		DWORD ThreadId=0;
		HANDLE h=CreateThread(NULL, 0,tf,this,0,&ThreadId);
		CloseHandle(h);
	}
	else
		tf(this);
}
DWORD WINAPI CPlaySound::tf(LPVOID lpParameter)//	static 
{
	CPlaySound* ps=(CPlaySound*)lpParameter;
	ps->Run();
	delete ps;
	return 0;
}
void CPlaySound::Run()
{
	if(m_nDuration)
	{
		PlaySound(m_sSound,NULL,SND_FILENAME|SND_LOOP|SND_ASYNC);
		if(WaitForSingleObject(m_hEventStop,m_nDuration*1000)==WAIT_TIMEOUT)
		{
			*m_psVal=NULL;
			HWND hW=FindWindow("#32770",g_szTitleMessage);
			if(hW)
			{
				PostMessage(hW,WM_CLOSE,0,0);
			}

		}
		PlaySound(m_sSound,NULL,SND_FILENAME|SND_PURGE);
	}
	else
	{
		PlaySound(m_sSound,NULL,SND_FILENAME|SND_SYNC);

	}

}

